<template>
  <view class="mark">
    <view class="t_right p_sm">
      <uni-icons
        type="close"
        size="30"
        color="#fff"
        @click="handleCancel"
      ></uni-icons>
    </view>
    <view class="swiper-container">
      <swiper
        class="swiper"
        :style="{ height: `${height}px` }"
        circular
        :indicator-dots="true"
        :current="index"
        :duration="duration"
        @change="handleChange"
      >
        <swiper-item v-for="item in urls" :key="item">
          <image
            class="image"
            mode="widthFix"
            :style="{ height: height }"
            :src="item"
          ></image>
        </swiper-item>
      </swiper>

      <view class="t_center">
        <uni-icons
          type="download"
          size="40"
          color="#fff"
          @click="download"
        ></uni-icons>
      </view>
    </view>
  </view>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import StyledImage from '../StyledImage.vue'
import { onLoad } from '@dcloudio/uni-app'

export default defineComponent({
  name: 'PreviewImage',
  components: {
    StyledImage,
  },
  props: {
    urls: {
      type: Array,
      default: () => [],
    },
  },
  setup(props, { emit }) {
    const index = ref(0)
    function download() {
      // #ifdef MP-WEIXIN
      uni.downloadFile({
        url: props.urls[index.value],
        success: (response) => {
          if (response.statusCode === 200) {
            const tempFilePath = response.data.tempFilePath

            uni.saveImageToPhotosAlbum({
              filePath: tempFilePath,
            })
          }
        },
      })
      // #endif

      // #ifdef WEB

      const DownLoad = document.createElement('a');
      DownLoad.download = `${new Date()}.png`;
      DownLoad.href = props.urls[index.value] || ''
      document.body.appendChild(DownLoad);
      DownLoad.click();
      DownLoad.remove(); // 下载之后把创建的元素删除

      // #endif
    }

    function handleChange(event) {
      index.value = event.detail.current
    }
    const handleCancel = () => {
      emit('vanish')
    }

    const height = ref(0)
    height.value = uni.getSystemInfoSync().windowHeight * 0.6

    return {
      download,
      index,
      handleChange,
      handleCancel,
      height,
    }
  },
})
</script>

<style lang="scss" scoped>
.mark {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  background: rgb(0, 0, 0, 1);
  z-index: 999;
}
.swiper-container {
  width: 100%;
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
}

.swiper {
  width: 100%;
  height: 500px;
}

.swiper-slide {
  text-align: center;
  font-size: 18px;
  background: #fff;

  height: 500px;
}

.image {
  width: 100%;
  height: 800px;
}

.btn {
  display: inline-block;
  margin: 8px;
  line-height: 1.8;
}
</style>
